#include <stdio.h>
#include <stdarg.h>
#include <time.h>

#include "Common.h"
#include "OS.h"

#define _FORMAT_BUF_SIZE 5*512

namespace WLog
{
	string stringFormat(const char* szFormat, ...)
	{
		char cBuf[_FORMAT_BUF_SIZE];

		va_list ap;

        va_start(ap, szFormat);

#ifdef MORE_AND_EQUAL_THAN_VC8_VS2005
        vsnprintf_s(cBuf, _FORMAT_BUF_SIZE, _TRUNCATE, szFormat, ap);
#else
        vsnprintf(cBuf, _FORMAT_BUF_SIZE, szFormat, ap);
#endif // MORE_AND_EQUAL_THAN_VC8_VS2005

        va_end(ap);
		
		return string(cBuf);
	}
	
	string vstringFormat(const char* szFormat, va_list ap)
	{
		char cBuf[_FORMAT_BUF_SIZE];

#ifdef MORE_AND_EQUAL_THAN_VC8_VS2005
        vsnprintf_s(cBuf, _FORMAT_BUF_SIZE, _TRUNCATE, szFormat, ap);
#else
        vsnprintf(cBuf, _FORMAT_BUF_SIZE, szFormat, ap);
#endif // MORE_AND_EQUAL_THAN_VC8_VS2005

		return string(cBuf);
	}

	string l2str(long lValue)
	{
		char cBuf[64];
		
#ifdef MORE_AND_EQUAL_THAN_VC8_VS2005
        _snprintf_s(cBuf, 64,64, "%ld", lValue);
#else
        snprintf(cBuf, 64, "%ld", lValue);
#endif // MORE_AND_EQUAL_THAN_VC8_VS2005

		return string(cBuf);
	}
	
	string getTimeStr(time_t time, const char* szFormat)
	{
#ifdef MORE_AND_EQUAL_THAN_VC8_VS2005
        tm timeinfo = {0};
        localtime_s(&timeinfo, &time);
        tm* tLocalTime = &timeinfo;
#else
        tm* tLocalTime = localtime(&time);
#endif // MORE_AND_EQUAL_THAN_VC8_VS2005
		char szTimeBuf[256];
		strftime(szTimeBuf, 256,  szFormat, tLocalTime);
		
		return string(szTimeBuf);
	}
	
	time_t now_time_t()
	{
		time_t timeNow;
		return time(&timeNow);
	}
	
}
